/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.blockly.utils;

import com.google.blockly.ohos.NinePatchElement;
import ohos.app.Context;
import ohos.global.resource.Resource;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import java.io.IOException;
import java.io.InputStream;

public class ImageUtils {

    public static NinePatchElement getPatchDrawable(Context context, int id) {
        Resource resource = null;
        try {
            resource = context.getResourceManager().getResource(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ImageSource imageSource = ImageSource.create(resource, new ImageSource.SourceOptions());
        PixelMap pixelMap = imageSource.createPixelmap(new ImageSource.DecodingOptions());
        return new NinePatchElement(pixelMap);
    }

    public static PixelMap getPixMap(Context context, int resId) {
        Resource resource = null;
        try {
            resource = context.getResourceManager().getResource(resId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ImageSource imageSource = ImageSource.create(resource, new ImageSource.SourceOptions());
        return imageSource.createPixelmap(new ImageSource.DecodingOptions());
    }

    public static PixelMap getRealSizePixelMap(PixelMap pixelMap, int width, int height) {
        PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
        initializationOptions.size = new Size(width, height);
        initializationOptions.pixelFormat = PixelFormat.ARGB_8888;
        initializationOptions.editable = true;
        return PixelMap.create(pixelMap, initializationOptions);
    }

    public static PixelMap inputStreamToPixelMap(InputStream inputStream) {
        try {
            if (inputStream != null) {
                try {
                    return ImageSource.create(inputStream, new ImageSource.SourceOptions())
                            .createPixelmap(new ImageSource.DecodingOptions());
                } finally {
                    inputStream.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
